//
//  HBRefreshControl.swift
//  MyWeiboApp
//
//  Created by 胡海波 on 15/7/4.
//  Copyright © 2015年 胡海波. All rights reserved.
//

import UIKit
import FFAutoLayout

class HBRefreshControl: UIRefreshControl {

    override init() {

        super.init()
        // 添加refreshView
        addSubview(refreshView)

        // 设置refreshView的布局
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))

        // 使用KVO监听
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)

    }

    // 使用kvo 一定要注销监听
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }

    /**
    1. 向下拉，y值会越来越小，Y值为负数，控件就会显示
    2. 拉到一定程度，会自动刷新
    3. 如果向上推表格，刷新控件仍然在，没有消失，Y值会一直变大
    */
    /// 显示提示图标标记
    private var showPullFlag = false
    /// 正在加载标记
    private var loadingFlag = false

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        if frame.origin.y > 0{
            return
        }

        if refreshing && !loadingFlag {
            refreshView.startLoadingAnimate()

            loadingFlag = true
            
            return
        }

        if frame.origin.y < -50 && !showPullFlag {

            showPullFlag = true
            refreshView.rotatePullIcon(showPullFlag)

        } else if frame.origin.y >= -50 && showPullFlag {

            showPullFlag = false
            refreshView.rotatePullIcon(showPullFlag)

        }

    }

    override func endRefreshing() {
        super.endRefreshing()

        // 关闭动画
        refreshView.stoploadingAnimate()

        // 重设刷新标记
        loadingFlag = false
    }



    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 懒加载
    lazy var refreshView = HBRefreshView.refreshView()
}

class HBRefreshView: UIView {

    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var pullRefreshView: UIView!
    @IBOutlet weak var pullRefreshIcon: UIImageView!


    class func refreshView() -> HBRefreshView {

        return NSBundle.mainBundle().loadNibNamed("HBRefreshControl", owner: nil, options: nil).last as! HBRefreshView
    }

    ///  旋转提示图标
    private func rotatePullIcon(clockWise: Bool) {

        var angle = M_PI

        angle += clockWise ? -0.01 : 0.01

        UIView.animateWithDuration(0.5) { () -> Void in

            self.pullRefreshIcon.transform = CGAffineTransformRotate(self.pullRefreshIcon.transform, CGFloat(angle))
        }
    }

    /// 开始加载动画
    private func startLoadingAnimate() {
        pullRefreshView.hidden = true

        let anim = CABasicAnimation(keyPath: "transform.rotation")

        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5

        loadingIcon.layer.addAnimation(anim, forKey: nil)
    }
    ///  停止动画
    private func stoploadingAnimate() {
        pullRefreshView.hidden = false

        loadingIcon.layer.removeAllAnimations()
    }


}